<?php require_once 'httpFilter.php'; 'conf.php'; ?>
<?php
$action = $_REQUEST["action"];
require_once "classes.php";
require_once "services/securityServices.php";
require_once "errorCodes.php";

$service = new CommonServices;

/** DB CONNECTION **/
$errCode = 0;
$errMessage = "";

$con = mysql_connect(GlobalConfig::db_host_name, GlobalConfig::db_username, GlobalConfig::db_password);
if (!$con) {
	die('Could not connect: ' . mysql_error());
}
mysql_select_db(GlobalConfig::db_name, $con);

/** DB CONNECTION END**/

if ($action == "getTransData") {
	$transId = $_REQUEST["transId"];

	$query = "select * from transaction where id=" . $transId;
	$result = mysql_query($query);

	if (!$result) {
		$errCode = 1;
	} else {
		$row = mysql_fetch_array($result);
		$description = $row["description"];
		$date = $row["date"];
		$transType = "";
		if ($row["amount"] < 0) {
			$transAmount = $row["amount"] * -1;
			$transType = "expense";
		} else {
			$transAmount = $row["amount"];
			$transType = "income";
		}
		$bankRef = $row["bankRef"];
		$budgetitemid = $row["budgetitemid"];
		$reconciled = $row["reconciled"];
	}
	echo "<result>";
	echo "<code>";
	echo $errCode;
	echo "</code>";
	echo "<transDescription>";
	echo $description;
	echo "</transDescription>";
	echo "<transDate>";
	echo "$date";
	echo "</transDate>";
	echo "<transAmount>";
	echo "$transAmount";
	echo "</transAmount>";
	echo "<bankRef>";
	echo $bankRef;
	echo "</bankRef>";
	echo "<transType>";
	echo $transType;
	echo "</transType>";
	echo "<reconciled>";
	echo $reconciled;
	echo "</reconciled>";
	echo "<transBudgetItemId>";
	echo $budgetitemid;
	echo "</transBudgetItemId>";

	$query = "select * from budgetitem";
	$result = mysql_query($query);

	if (!$result) {
		$errCode = 1;
	} else {
		while ($row = mysql_fetch_array($result)) {
			echo "<category>";
			echo "<id>";
			echo $row["categoryId"];
			echo "</id>";
			echo "<budgetItemId>";
			echo $row["id"];
			echo "</budgetItemId>";
			echo "<catDescription>";
			echo $row["description"];
			echo "</catDescription>";
			echo "<expense>";
			echo $row["expense"];
			echo "</expense>";
			echo "</category>";
		}
	}

	//We fetch accounts
	$query = "select * from account";
	$result = mysql_query($query);

	if (!$result) {
		$errCode = 1;
	} else {
		while ($row = mysql_fetch_array($result)) {
			echo "<category>";
			echo "<id>";
			echo "6";
			echo "</id>";
			echo "<budgetItemId>";
			echo $row["id"];
			echo "</budgetItemId>";
			echo "<catDescription>";
			echo $row["name"];
			echo "</catDescription>";
			echo "<expense>";
			echo "0";
			echo "</expense>";
			echo "</category>";
		}
	}

	echo "</result>";
} else	if ($action == "saveTransType") {

	$description = $_REQUEST["description"];
	$expense = $_REQUEST["expense"];

	$query = "insert into transaction_type (description, expense) values ('" . $description . "', " . $expense . ")";
	$result = mysql_query($query);
	if (!$result) {
		$errCode = 1;
	}
	echo "<result>";
	echo "<code>";
	echo $errCode;
	echo "</code>";
	echo "</result>";

} else	if ($action == "saveTransaction") {

	$transId = $_REQUEST["transId"];
	$transDate = $_REQUEST["transDate"];
	$transDescription = $_REQUEST["transDescription"];
	$autoReconcile = $_REQUEST["autoReconcile"];
	$transDescriptor = $_REQUEST["transDescriptor"];
	$categoryId = $_REQUEST["categoryId"];
	$reconciled = $_REQUEST["reconciled"];
	$transAmount = $_REQUEST["transAmount"];
	$budgetItemId = $_REQUEST["budgetItemId"];
	$accId = $_REQUEST["accId"];

	if ($transId == ""){
		/** INSERT TRANSACTION **/
		$query = "insert into transaction (accountId, date, amount, description, reconciled, categoryId, budgetitemid) values (". $accId .", '" . $transDate . "', ". $transAmount .", '". $transDescription ."', true, ". $categoryId .", ".  $budgetItemId .")";
	} else {
		/** UPDATE TRANSANCTION **/
		$query = "update transaction set date='" . $transDate . "', amount=" . $transAmount . ", description='" . $transDescription . "', reconciled=true, categoryId=" . $categoryId . ", budgetitemid=" . $budgetItemId . " where id=" . $transId;
	}

	error_log($query);
	$result = mysql_query($query);
	if (!$result) {
		$errCode = 1;
	}

	//If it's a savings transfer transaction
	$savingsAccId = $service->getSavingsAccountId();
	if ($categoryId == 4) {
		$query = "insert into transaction (accountId, date, amount, description, reconciled, categoryId, budgetitemid, parentTransId) values (". $savingsAccId .", '". $transDate ."', ". $transAmount .", '". $transDescription ."', 0, 4, ". $budgetItemId .", 0)";
		error_log($query);
		$result = mysql_query($query);
		if (!$result) {
			$errCode = 1;
		}
	}

	error_log("ACCOUNT NAME: ".$transDescriptor);

	//If it is a transfer transaction
	if ($categoryId == 6) {
		$accountId = $budgetItemId;
		$query = "insert into transaction (accountId, date, amount, description, reconciled, categoryId) values (". $accountId .", '". $transDate ."', ". ($transAmount * -1) .", 'Transfer', 1, 6)";
		error_log($query);
		$result = mysql_query($query);
		if (!$result) {
			$errCode = 1;
		}
	}

	/** DEFINE AUTO_RECONCILE **/
	if ($autoReconcile == "true") {
		$query = "insert into autoreconcile values ('" . $transDescriptor . "'," . $budgetItemId . ")";
		error_log($query);
		$result = mysql_query($query);
		if (!$result) {
			$errCode = 1;
		}

		$query = "update transaction set reconciled=1, categoryId=" . $categoryId . ", description='" . $transDescription . "', budgetitemid=" . $budgetItemId . " where reconciled=0 and bankRef like '%" . $transDescriptor . "%'";
		error_log($query);
		$result = mysql_query($query);
		if (!$result) {
			$errCode = 1;
		}
	}

	echo "<result>";
	echo "<code>";
	echo $errCode;
	echo "</code>";
	echo "</result>";

} else	if ($action == "getSavingsTransactions") {
	$categoryId = $_REQUEST["categoryId"];
	$budgetItemId = $_REQUEST["budgetItemId"];
	$accountId = $_REQUEST["accountId"];

	$query = "select * from transaction where budgetitemid=" . $budgetItemId . " and categoryId=4 and accountId=" . $accountId;
	error_log($query);
	$result = mysql_query($query);
	if (!$result) {
		$errCode = 1;
	}

	echo "<result>";
	echo "<code>";
	echo $errCode;
	echo "</code>";
	while ($row = mysql_fetch_array($result)) {
		echo "<transaction>";
		echo "<id>";
		echo $row["id"];
		echo "</id>";
		echo "<budgetitemid>";
		echo $row["budgetitemid"];
		echo "</budgetitemid>";
		echo "<date>";
		echo $row["date"];
		echo "</date>";
		echo "<description>";
		echo $row["description"];
		echo "</description>";
		echo "<amount>";
		echo $row["amount"];
		echo "</amount>";
		echo "</transaction>";
	}
	echo "</result>";
} else	if ($action == "registerSavings") {
	$services = new CommonServices();
	$budgetId = $_REQUEST["budgetId"];
	$expenseSavingsActuals = split(",", $_REQUEST["expenseSavingsActual"]);
	$budgetItemIds = split(",", $_REQUEST["expenseSavingsRowId"]);
	$expenseSavingsDescriptions = split(",", $_REQUEST["expenseSavingsDescription"]);

	$count = 0;
	foreach ($budgetItemIds as $row) {
		if ($count != 0) {

			$query = "insert into  transaction (accountId, date, amount, description, reconciled, categoryId, budgetitemid, parentTransId) values (" . $services->getSavingsAccountId(). ", NOW()," . $expenseSavingsActuals[$count] . ", '" . $expenseSavingsDescriptions[$count] . "', 0, 4, " . $budgetItemIds[$count] . ", 0)";
			error_log($query);
			$result = mysql_query($query);
			if (!$result) {
				$errCode = 1;
			}
		}
		$count = $count +1;
	}
	echo "<result>";
	echo "<code>";
	echo $errCode;
	echo "</code>";
	echo "</result>";
} else if ($action == "doSavingsReconcile"){
	$accId = $_REQUEST["accId"];
	$mainTransId = $_REQUEST["mainTransId"];
	$description = $_REQUEST["reconTransDescription"];
	$transId =  split(",",$_REQUEST["transId"]);
	$newTransDate =  split(",",$_REQUEST["newTransDate"]);
	$newTransDescription =  split(",",$_REQUEST["newTransDescription"]);
	$newTransAmount =  split(",",$_REQUEST["newTransAmount"]);
	$newTransBudgetItemId =  split(",",$_REQUEST["newTransBudgetItemId"]);

	//Update main transaction
	$query = "update transaction set reconciled = true where id=". $mainTransId;
	error_log($query);
	$result = mysql_query($query);
	if (!$result) {
		$errCode = 1;
	}

	//We update the existing subtractions
	$count=0;
	foreach ($transId as  $row){
		if($count != 0){
			$query = "update transaction set reconciled = true, parentTransId=". $mainTransId ." where id=". $transId[$count];
			error_log($query);
			$result = mysql_query($query);
			if(!$result){
				$errCode=1;
			}
		}
		$count++;
	}

	$count=0;
	foreach ($newTransDate as  $row){
		if($count != 0){
			$query = "insert into transaction (accountId, date, amount, description, reconciled, categoryId, budgetitemid, parentTransId) values (". $accId .", '". $newTransDate[$count] ."', ". $newTransAmount[$count] .", '". $newTransDescription[$count] ."', 1, 4, ". $newTransBudgetItemId[$count] .", ". $mainTransId .")";
			error_log($query);
			$result = mysql_query($query);
			if(!$result){
				$errCode=1;
			}
		}

		$count++;
	}

	echo "<result>";
	echo "<code>";
	echo $errCode;
	echo "</code>";
	echo "</result>";

} else if ($action == "getCategories"){
	$query = "select * from budgetitem";
	$result = mysql_query($query);

	echo "<result>";
	if (!$result) {
		$errCode = 1;
	} else {
		while ($row = mysql_fetch_array($result)) {
			echo "<category>";
			echo "<id>";
			echo $row["categoryId"];
			echo "</id>";
			echo "<budgetItemId>";
			echo $row["id"];
			echo "</budgetItemId>";
			echo "<catDescription>";
			echo $row["description"];
			echo "</catDescription>";
			echo "<expense>";
			echo $row["expense"];
			echo "</expense>";
			echo "</category>";
		}
	}

	//We fetch accounts
	$query = "select * from account";
	$result = mysql_query($query);

	if (!$result) {
		$errCode = 1;
	} else {
		while ($row = mysql_fetch_array($result)) {
			echo "<category>";
			echo "<id>";
			echo "6";
			echo "</id>";
			echo "<budgetItemId>";
			echo $row["id"];
			echo "</budgetItemId>";
			echo "<catDescription>";
			echo $row["name"];
			echo "</catDescription>";
			echo "<expense>";
			echo "0";
			echo "</expense>";
			echo "</category>";
		}
	}

	echo "</result>";
} else if ($action == "deleteTransaction"){
	$transactionId = $_REQUEST["transactionId"];

	$query = "delete from transaction where id=". $transactionId;
	$result = mysql_query($query);

	if (!$result) {
		$errCode = 1;
	}

	echo "<result>";
	echo "<code>";
	echo $errCode;
	echo "</code>";
	echo "</result>";

} else if ($action == "createAccount"){
	$accountName = $_REQUEST["accountName"];
	$accountNum = $_REQUEST["accountNum"];
	$openingBal = $_REQUEST["openingBal"];
	$accountType = $_REQUEST["accountType"];

	if ($accountType == "expenseSavings"){
		$accountType = 1;
	} else if ($accountType == "normal"){
		$accountType = 0;
	}

	$query = "insert into account (name, accNum, creationdate, active, balance, stmtBalance, openingBalance, type) values ('". $accountName ."', '". $accountNum ."', Now(), 1, 0, 0, ". $openingBal .", ". $accountType .")";
	error_log($query);
	$result = mysql_query($query);

	if (!$result) {
		$errCode = 1;
	}

	echo "<result>";
	echo "<code>";
	echo $errCode;
	echo "</code>";
	echo "</result>";
} else if ($action == "getCategoryItems"){
	$categoryId = $_REQUEST["categoryId"];
	$budgetId = $_REQUEST["budgetId"];

	//We first fetch the budgetitems available in this budget
	$query = "select * from budget_budgetitem where budgetid=". $budgetId;
	error_log($query);
	$result = mysql_query($query);
	if (!$result) {
		$errCode = 1;
	}
	$existingBudgetItems = array();
	while ($row = mysql_fetch_array($result)) {
		array_push($existingBudgetItems, $row["budgetitemid"]);
	}


	//We fetch the budgetitems
	$query = "select * from budgetitem where categoryId=". $categoryId;
	error_log($query);
	$result = mysql_query($query);

	echo "<result>";
	if (!$result) {
		$errCode = 1;
	} else {
		while ($row = mysql_fetch_array($result)) {
			if (in_array($row["id"], $existingBudgetItems)){
				continue;
			}
			echo "<category>";
			echo "<id>";
			echo $row["id"];
			echo "</id>";
			echo "<catDescription>";
			echo $row["description"];
			echo "</catDescription>";
			echo "</category>";
		}
	}
	echo "<code>";
	echo $errCode;
	echo "</code>";
	echo "</result>";
} else if ($action == "getReport"){
	$reportType= $_REQUEST["reportType"];
	$toDate= $_REQUEST["toDate"];
	$fromDate= $_REQUEST["fromDate"];
	$savingsAccId = $service->getSavingsAccountId();

	if($reportType=="incomeAndExpense"){
		$query = "select t.id, t.date, t.description, t.amount, t.categoryId from transaction t, account a where t.accountId=a.id and a.type=0 and date(date) >= '". $fromDate ."' and date(date) < '". $toDate ."'";
		error_log($query);
		$result = mysql_query($query);

		echo "<result>";
		if (!$result) {
			$errCode = 1;
		} else {
			while ($row = mysql_fetch_array($result)) {
				echo "<transaction>";
				echo "<id>";
				echo $row["id"];
				echo "</id>";
				echo "<date>";
				echo $row["date"];
				echo "</date>";
				echo "<description>";
				echo $row["description"];
				echo "</description>";
				echo "<amount>";
				echo $row["amount"];
				echo "</amount>";
				echo "<categoryId>";
				echo $row["categoryId"];
				echo "</categoryId>";
				echo "</transaction>";

			}
		}
	}else if($reportType=="categories"){
		//		$query = "select * from transaction where accountId<>". $savingsAccId ." and accountId<>4 and date(date) >= '". $fromDate ."' and date(date) < '". $toDate ."'";
		$query = "select t2.description description, t2.id id , sum(t1.amount) amount from transaction t1, budgetitem t2  where t1.budgetitemid = t2.id and accountId<>". $savingsAccId ." and accountId<>4 and date(date) >= '". $fromDate ."' and date(date) < '". $toDate ."' group by t2.description, t2.id";
		error_log($query);
		$result = mysql_query($query);

		echo "<result>";
		if (!$result) {
			$errCode = 1;
		} else {
			while ($row = mysql_fetch_array($result)) {
				echo "<transaction>";
				echo "<id>";
				echo $row["id"];
				echo "</id>";
				echo "<description>";
				echo $row["description"];
				echo "</description>";
				echo "<amount>";
				echo $row["amount"];
				echo "</amount>";
				echo "</transaction>";
			}
		}
	}
	echo "<code>";
	echo $errCode;
	echo "</code>";
	echo "</result>";
} else if ($action == "loginUser"){
	try {
		$securityService = new SecurityService;
		$username = $_REQUEST["username"];
		$password = $_REQUEST["password"];

		$resutl = $securityService->loginUser($username, $password);

		if ($resutl == "true"){
			$errCode = 0;
			session_start();
			$_SESSION["username"] = $username;
			$_SESSION["password"] = $password;
		} else {
			$errCode = 1;
			$errMessage = "Invalid credentials. Try again.";
		}
	} catch (Exception $e) {
		print "Error!: " . $e->getMessage() . "<br/>";
		$errCode = $e->getMessage();
		$errorCodes = new ErrorCodes;
		$errMessage = $errorCodes->getErrorMessage($e->getMessage());
	}


	echo "<result>";
	echo "<code>";
	echo $errCode;
	echo "</code>";
	echo "<errMessage>";
	echo $errMessage;
	echo "</errMessage>";
	echo "</result>";
}

mysql_close($con);
?>